﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

using SYcwpb.ViewModels;
using SYcwpb.Helpers;
using System.Data;
using Microsoft.Windows.Controls;
using System.Threading;
using System.IO;


namespace SYcwpb.Views
{
    /// <summary>
    /// StatisticsView.xaml 的交互逻辑
    /// </summary>
    public partial class StatisticsView : Window
    {
        public static StatisticsView _view = null;
        private StatisticsViewModel _viewModel;

        public static StatisticsView GetInstance()
        {
            if (null == _view || WindowHelper.IsDisposed(_view))
                _view = new StatisticsView();

            return _view;
        }

        public StatisticsView()
        {
            InitializeComponent();

            _viewModel = new StatisticsViewModel(this);

            this.DataContext = _viewModel;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
           // _viewModel
            
        }

        public void SetView_dgv_Visibility()
        {

            Style totalStyle = new Style();

            if (view_safemiles_dgv.Columns.Count > 0)
                if (view_safemiles_dgv.Columns[0].Visibility != Visibility.Collapsed)
                {
                    view_safemiles_dgv.Columns[0].Visibility = Visibility.Collapsed;
                    //view_safemiles_dgv.Columns[4].
                }

            if (view_followmiles_dgv.Columns.Count > 0)
                if (view_followmiles_dgv.Columns[0].Visibility != Visibility.Collapsed)
                {
                    view_followmiles_dgv.Columns[0].Visibility = Visibility.Collapsed;
                }

            if (view_hours_dgv.Columns.Count > 0)
                if (view_hours_dgv.Columns[0].Visibility != Visibility.Collapsed)
                {
                    view_hours_dgv.Columns[0].Visibility = Visibility.Collapsed;
                }
        }

        private void auto_dgv_PreviewExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            if (e.Command == DataGrid.DeleteCommand)
            {
                if (MessageBoxHelper.ConfirmYesNo("确定要删除该行记录吗？"))
                {
                    DataRowView rowView = auto_dgv.SelectedItem as DataRowView;
                    if (null != rowView)
                        _viewModel.DeleAutoDgvRow(rowView.Row);
                }
                else
                    e.Handled = true;
            }
        }

        private void Manaual_DatePicker_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            _viewModel.Manaual_SelectDateResult();
        }

        private void Manaual_DataGrid_PreviewExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            if (e.Command == DataGrid.DeleteCommand)
            {
                if (!MessageBoxHelper.ConfirmYesNo("确定要删除该行吗？"))
                {
                    e.Handled = true;
                    return;
                }
                DataRowView rowView = manaual_dgv.SelectedItem as DataRowView;
                if (rowView != null)
                    if (!_viewModel.Manaual_DeleteRow(rowView.Row))
                    {
                        e.Handled = true;
                        MessageBoxHelper.ShowError("删除失败：尝试删除该行过程中出现异常");
                    }
                    else
                        MessageBoxHelper.ShowError("删除该行记录成功！");
            }
        }

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {

                int index = -1;
                if (_viewModel.ManualStaResultDT!=null&&_viewModel.ManualStaResultDT.Rows.Count>0&&_viewModel.Manaual_CheckhasDriverRecod(ref index))
                {
                    DataRow row = _viewModel.ManualStaResultDT.Rows[index];
                    if (row["PostName"].ToString() == "电客车司机")
                    {
                        _viewModel.Mana_Miles = row["SafeMiles"].ToString();
                    }
                    else
                    {
                        _viewModel.Mana_Miles = row["FollowMiles"].ToString();
                    }
                    _viewModel.Mana_Hours = row["WorkHours"].ToString();
                }
                //
            }
            catch (System.Exception ex)
            {
                MessageBoxHelper.ShowError(ex);
            }
            
        }
        public delegate void ExportExcelHandler(string path,DateTime start,DateTime end);
        private Thread ExportExcelThread = null;
        private void btnExportStatistics_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                
                int days = (_viewModel.View_EndDate - _viewModel.View_StartDate).Days;
                if (days < 0)
                {
                    MessageBoxHelper.ShowError("请选择开始日期小于截止日期!");
                    return;
                }
                if (days > 180)
                {
                    MessageBoxHelper.ShowError("请选择日期跨度小于六个月");
                }
                string filePath = MessageBoxHelper.ConfirmPath("请选择导出路径");
                if (string.IsNullOrEmpty(filePath))
                    return;

                ExportErroredEvent = new delExportHandler(OnExportErrored);
                ExportFinishedEvent = new delExportHandler(OnExportFinished);

                if (ExportExcelThread != null)
                {
                    ExportExcelThread.Abort();
                }
                ExportExcelThread = new Thread(delegate() { ExportStatisticsExcel(filePath, _viewModel.View_StartDate, _viewModel.View_EndDate); });
                ExportExcelThread.SetApartmentState(ApartmentState.STA);
                ExportExcelThread.IsBackground = true;
                ExportExcelThread.Start();
            }
            catch (Exception ex)
            {
                MessageBoxHelper.ShowError(ex);
            }
        }

        private void ExportStatisticsExcel(string path, DateTime start, DateTime end)
        {
            try
            {
                int days = (end - start).Days;
                string filename = string.Format("公里数统计_{0}.xlsx", DateTime.Now.ToString("yyyy-MM-dd HH_mm_ss"));
                DataTable View_SafeMilesDT = _viewModel.StatisticsAccess.GetViewMilesDT(start, days, 1);
                DataTable safeMilesRecordDT = _viewModel.StatisticsAccess.getSafeMilesRecordInDays(_viewModel.View_StartDate.ToString("yyyy-MM-dd"), _viewModel.View_EndDate.ToString("yyyy-MM-dd"));

                OutExcel excel = new OutExcel();
                //excel.SetCellValue()
                excel.Close();
                excel.KillExcelProcess();
                OnExportFinished(filename);
            }
            catch (Exception ex)
            {
                OnExportErrored(ex.Message+ex.StackTrace);
            }
        }
        delegate void delExportHandler(string str);
        private event delExportHandler ExportFinishedEvent;
        private event delExportHandler ExportErroredEvent;
        private void OnExportFinished(string file)
        {
            MessageBoxHelper.ShowTips(string.Format("导出 {0}  成功!", file));
        }
        private void OnExportErrored(string msg)
        {
            MessageBoxHelper.ShowError(msg);
        }
        //private void Gen
    }
}
